package sush.global.cammail;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import sush.global.cammail.actionbar.ActionBarActivity;
import sush.global.cammail.provider.Scheme;

public class TemplateActivity extends ActionBarActivity {
	
	private int _templateId;
	private ContentValues _templateRow;
	
	private TextView _warningView;
	private LinearLayout _layout;
	private ListView _fieldslist;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Template");
		super.addMenuIds(new int[] {R.id.menu_back, R.id.menu_add});
		setContentView(R.layout.template);
		
		try {
			Bundle extras = getIntent().getExtras();
			_templateId = extras.getInt("template_id");
		} catch(Exception e) {
			_templateId = -1;
		}
		
		_layout = (LinearLayout)findViewById(R.id.layout);
		_warningView = (TextView)findViewById(R.id.nofields);
		_fieldslist = (ListView)findViewById(R.id.listview);
		_fieldslist.setOnHierarchyChangeListener(fieldListChanged);
		
		loadData();
	}
	
	@Override
	public void onStop() {
		EditText titleText = (EditText)findViewById(R.id.title);
		String newText = titleText.getText().toString();
		String oldText = _templateRow.getAsString(Scheme.getTemplateTable().COLUMN_NAME_NAME);
		if(!newText.equals(oldText)) {
			_templateRow.put(Scheme.getTemplateTable().COLUMN_NAME_NAME, newText);
			getContentResolver().update(
					Scheme.getTemplateTable().getContentUri(),
					_templateRow,
					Scheme.getTemplateTable()._ID + "=?",
					new String[] { Integer.toString(_templateId) });
			getContentResolver().notifyChange(Scheme.getTemplateTable().getContentUri(), null);
		}
		super.onStop();
	}
	
	private void loadData() {		
		if(_templateId <= 0) {
			Time time = new Time();
			time.setToNow();
			ContentValues values = new ContentValues();
			values.put(Scheme.getTemplateTable().COLUMN_NAME_NAME, "Template "+time.format2445());
			Uri uri = getContentResolver().insert(Scheme.getTemplateTable().getContentUri(), values);
			_templateId = Integer.parseInt(uri.getLastPathSegment());
		}
		// Let fill EditView
		String whereClause = Scheme.getTemplateTable()._ID + "=?";
		Cursor cursor = getContentResolver().query(
				Scheme.getTemplateTable().getContentUri(),
				null,
				whereClause,
				new String[] { Integer.toString(_templateId) },
				null);
		cursor.moveToFirst();
		_templateRow = new ContentValues();
		DatabaseUtils.cursorRowToContentValues(cursor, _templateRow);
		cursor.close();
		EditText titleView = (EditText)findViewById(R.id.title);
		titleView.setText(_templateRow.getAsString(Scheme.getTemplateTable().COLUMN_NAME_NAME));
		
		// Let fill ListView
		whereClause = Scheme.getFieldTable().COLUMN_NAME_IDTEMPLATE + "=?";
		cursor = getContentResolver().query(
				Scheme.getFieldTable().getContentUri(),
				null,
				whereClause,
				new String[] { Integer.toString(_templateId) },
				null);
		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.listitem_with_add,
				cursor,
				new String[] { Scheme.getFieldTable().COLUMN_NAME_LABEL },
				new int[] { R.id.title });
		_fieldslist.setAdapter(adapter);
		_fieldslist.setOnItemClickListener(fieldClicked);
		
		if(cursor.getCount() > 0) {
			_layout.removeView(_warningView);
		}
	}
	
	private OnItemClickListener fieldClicked = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> list, View view, int position, long id) {
			Cursor cursor = ((SimpleCursorAdapter)_fieldslist.getAdapter()).getCursor();
			cursor.moveToPosition(position);
			final ContentValues values = new ContentValues();
			DatabaseUtils.cursorRowToContentValues(cursor, values);
			
			Intent intent = new Intent(TemplateActivity.this, FieldTemplateActivity.class);
			intent.putExtra("template_id", _templateId);
			intent.putExtra("field_id", values.getAsInteger(Scheme.getFieldTable()._ID));
			startActivity(intent);
		}
	};
	
	private OnHierarchyChangeListener fieldListChanged = new OnHierarchyChangeListener() {
		@Override
		public void onChildViewRemoved(View parent, View child) {
			if(_fieldslist.getCount() == 0)
				_layout.addView(_warningView, 2);
		}
		
		@Override
		public void onChildViewAdded(View parent, View child) {
			if(_fieldslist.getCount() > 0 && _layout.findViewById(R.id.nofields) != null)
					_layout.removeView(_warningView);
		}
	};
	
	public void deleteClicked(View view) {
		int position = _fieldslist.getPositionForView((View)view.getParent());
		final Cursor cursor = ((SimpleCursorAdapter)_fieldslist.getAdapter()).getCursor();
		cursor.moveToPosition(position);
		final ContentValues values = new ContentValues();
		DatabaseUtils.cursorRowToContentValues(cursor, values);
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Are you sure?");
		alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String fieldId = values.getAsString(Scheme.getFieldTable()._ID);
				deleteValuesForField(fieldId);
				String whereClause = Scheme.getFieldTable()._ID + "=?";
				getContentResolver().delete(
						Scheme.getFieldTable().getContentUri(),
						whereClause,
						new String[] { fieldId });
			}
		});
		alertDialog.setNegativeButton("Cancel", null);
		alertDialog.show();
	}
	
	private void deleteValuesForField(String fieldId) {
		String whereClause = Scheme.getDropDownValueTable().COLUMN_NAME_IDFIELD + "=?";
		String[] whereArgs = new String[] { fieldId };
		getContentResolver().delete(Scheme.getDropDownValueTable().getContentUri(), whereClause, whereArgs);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.add, menu);
        return super.onCreateOptionsMenu(menu);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.menu_back:
    			finish();
    			break;
    		case R.id.menu_add:
    			Intent intentField = new Intent(this, FieldTemplateActivity.class);
    			intentField.putExtra("template_id", _templateId);
    			startActivity(intentField);
    			break;
    		case R.id.home_button:
    			Intent intent = new Intent(this, MainActivity.class);
    			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			startActivity(intent);
    			break;
    		default:
    			return super.onOptionsItemSelected(item);
    	}
    	return true;
    }
}
